package com.xiaoyang.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoyang.common.core.domain.TableDataInfo;
import com.xiaoyang.friend.domain.question.Question;
import com.xiaoyang.friend.domain.question.dto.QuestionQueryDTO;
import com.xiaoyang.friend.domain.question.es.QuestionES;
import com.xiaoyang.friend.domain.question.vo.QuestionDetailVO;
import com.xiaoyang.friend.domain.question.vo.QuestionVO;
import com.xiaoyang.friend.elasticsearch.QuestionRepository;
import com.xiaoyang.friend.manager.QuestionCacheManager;
import com.xiaoyang.friend.mapper.quesion.QuestionMapper;
import com.xiaoyang.friend.service.question.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    /**
     * 题目列表
     * @param questionQueryDTO
     */
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        log.info("题目列表");
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);

        String keyword = questionQueryDTO.getKeyword(); // 题目关键词
        Integer difficulty = questionQueryDTO.getDifficulty(); // 题目难度
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) { // 搜索全部题目
          questionESPage = questionRepository.findAll(pageable);
        } else if (difficulty == null) { // 根据标题搜索题目
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else if (StrUtil.isEmpty(keyword)) { // 根据题目难度搜索题目
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else { // 根据标题和题目难度搜索题目
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long total = questionESPage.getTotalElements(); // 题目总数
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    /**
     * 根据题目id获取题目详情
     * @param questionId
     * @return
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        log.info("题目详情:" + questionId);
        // 从ES中查询题目是否存在
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        // 如何在ES中查询不到题目，则从数据库中查询
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        // 从数据库中查询到题目，则刷新ES
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    /**
     * 获取上一道题目
     * @param questionId
     * @return
     */
    @Override
    public String preQuestion(Long questionId) {
        log.info("获取{}的上一道题目:" , questionId);
        // 从redis中查询题目是否存在
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            // redis中没有数据，则刷新redis
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    /**
     *
     * @param questionId
     * @return
     */
    @Override
    public String nextQuestion(Long questionId) {
        log.info("获取{}的下一道题目:" , questionId);
        // 从redis中查询题目是否存在
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            // redis中没有数据，则刷新redis
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    /**
     * 从数据库中刷新题目列表
     */
    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
